<template>
  <a-modal
    :title="title"
    :width="840"
    :visible="visible"
    :confirmLoading="loading"
    @ok="() => { $emit('ok', model) }"
    @cancel="handleCancel"
    :footer="null"
    :destroyOnClose="true"
  >
    <a-spin :spinning="loading">

    </a-spin>
    <div class="steps-content">
<!--      第一步-->
      <div v-if="current === 0">
        <a-form :form="form" v-bind="formLayout">
          <!-- 检查是否有 id 并且大于0，大于0是修改。其他是新增，新增不显示主键ID -->
          <a-form-item v-show="false" label="主键ID">
            <a-input v-decorator="['id', { }]" disabled />
          </a-form-item>
          <a-form-item label="名称">
            <a-input v-decorator="['wsName', {rules: [{required: true, message: '名称必填'}]}]" />
          </a-form-item>
          <a-form-item label="所属应用">
            <a-cascader
              :options="options"
              :show-search="{ filter }"
              :display-render="displayRender"
              placeholder="Please select"
              expand-trigger="hover"
              v-decorator="['visualData', {initialValue: []}]"
            />
          </a-form-item>
          <a-form-item label="From" v-if="mode === 'Add'">
            <a-select
              show-search
              allowClear
              placeholder="Select a source"
              option-filter-prop="children"
              :filter-option="filterOption"
              @change="handleChange"
              v-decorator="['source', {initialValue: ''}]"
            >
              <a-select-option value="mingdao">
                明道云
              </a-select-option>
            </a-select>
          </a-form-item>
          <template v-if="source === 'mingdao'">
            <a-form-item label="Url">
              <a-input v-decorator="['md_url', {initialValue: '', rules: [{required: true, pattern: new RegExp('^http(s)?://([\\w-]+\\.)+[\\w-]+(:[1-9][0-9][0-9][0-9])?(/[\\w-./?%&=]*)?$', 'g'), message: 'url格式错误'}]}]" />
            </a-form-item>
            <a-form-item label="App Key">
              <a-input v-decorator="['md_appKey', {initialValue: '', rules: [{required: true, message: '必填'}]}]" />
            </a-form-item>
            <a-form-item label="Sign">
              <a-input v-decorator="['md_sign', {initialValue: '', rules: [{required: true, message: '必填'}]}]" />
            </a-form-item>
          </template>
        </a-form>
      </div>
<!--      第二步-->
      <div v-if="current === 1">
        <a-form v-bind="formLayout">
        <a-form-item label="表单">
          <a-cascader
            :options="md.worksheets"
            :show-search="{ filter }"
            :display-render="displayRender"
            placeholder="Please select a worksheet"
            @change="onChange"
            expand-trigger="hover"
          />
        </a-form-item>
          <a-form-item label="视图" v-if="mdParams.worksheetId">
            <a-select
              show-search
              allowClear
              placeholder="Select a view"
              option-filter-prop="children"
              :filter-option="filterOption"
              v-model="mdParams.viewId"
            >
              <a-select-option
                v-for="view in md.views"
                :key="view.viewId"
                :value="view.viewId"
              >
                {{ view.name }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="字段" v-if="mdParams.worksheetId">
            <a-select
              mode="multiple"
              show-search
              allowClear
              placeholder="Please select fields"
              option-filter-prop="children"
              :filter-option="filterOption"
              v-model="mdParams.fields"
            >
              <a-select-option
                v-for="field in md.fields"
                :key="field.controlId"
                :value="field.controlId"
              >
                {{ field.controlName }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </div>
      <div v-if="current === 2">
        选择字段
      </div>
    </div>
    <div class="steps-action">
      <a-button v-if="current > 0" @click="prev">
        上一步
      </a-button>
      <a-button v-if="current < steps.length - 1 && source" style="margin-left: 8px" type="primary" @click="next">
        下一步
      </a-button>
<!--      <a-button-->
<!--        v-if="mode === 'Edit'"-->
<!--        type="text"-->
<!--      >-->
<!--        绑定更多应用-->
<!--      </a-button>-->
      <a-button
        v-if="current === steps.length - 1 || !source"
        type="primary"
        style="margin-left: 8px"
        @click="handleOk"
      >
        确认
      </a-button>
    </div>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { getApp, getCascadeData, getMdWorksheet, saveMdStruct } from '@/api/worksheet'

// 表单字段
const fields = ['wsName', 'id', 'visualData', 'source', 'md_url', 'md_appKey', 'md_sign']

export default {
  props: {
    visible: {
      type: Boolean,
      required: true
    },
    loading: {
      type: Boolean,
      default: () => false
    },
    model: {
      type: Object,
      default: () => null
    },
    options: {
      type: Array,
      default: () => []
    },
    mode: {
      type: String,
      default: () => "Edit"
    }
  },
  data () {
    this.formLayout = {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      }
    }
    return {
      form: this.$form.createForm(this),
      // options: [],
      source: '',
      current: 0,
      steps: [
        {
          title: '表单信息',
          content: 'First-content',
        },
        {
          title: '选择表单',
          content: 'Last-content',
        },
      ],
      md: {
        app: {},
        worksheets: [],
        views: [],
        fields: [],
      },
      mdParams: {
        worksheetId: '',
        viewId: '',
        fields: [],
      },
      mdl: {},
    }
  },
  computed: {
    title: function () {
      return this.steps[this.current].title
    }
  },
  methods: {
    handleCancel () {
      this.form.resetFields()
      this.backToDefaultValue()
      this.$emit('cancel')
    },
    clearMdParams () {
      this.mdParams = {
        worksheetId: '',
        viewId: '',
        fields: [],
      }
    },
    onChange (value, selectedOptions) {
      // console.log(value, selectedOptions)
      this.clearMdParams()
      this.mdParams.worksheetId = value[1]
      const param = Object.assign({ "worksheetId": value[1] }, this.mdl._md)
      getMdWorksheet(param).then(res => {
        // console.log('mdWs', res)
        if (res.success) {
          const { views, controls } = res.data
          this.md.views = views
          this.mdParams.viewId = views[0].viewId
          this.md.fields = controls
        }
      })
    },
    filter (inputValue, path) {
      return path.some(option => option.label.toLowerCase().indexOf(inputValue.toLowerCase()) > -1);
    },
    displayRender ({ labels }) {
      return labels[labels.length - 1];
    },
    handleChange (value) {
      // console.log(`selected ${value}`);
      this.source = value
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      );
    },
    next () {
      this.handleSecondStep().then(() => {
        this.current++
      }).catch(e => {})
    },
    prev () {
      if (this.current === 1) {
        this.clearMdParams()
        fields.forEach(v => this.form.getFieldDecorator(v))
        this.form.setFieldsValue(this.mdl)
      }
      this.current--
    },
    handleOk () {
      console.log('ok', this.mdParams, this.mdl, this.md)
      if (!this.source) {
        this.$emit("ok")
      } else {
        // 保存明道的表格
        const data = {
          wsName: this.mdl.wsName,
          visualData: this.mdl.visualData,
          controls: this.md.fields.filter(f => this.mdParams.fields.includes(f.controlId)),
          baseUrl: this.mdl.md_url,
          appKey: this.mdl.md_appKey,
          sign: this.mdl.md_sign,
          appId: this.md.app.appId,
          worksheetId: this.mdParams.worksheetId,
          viewId: this.mdParams.viewId
        }
        saveMdStruct(data).then(res => {
          // console.log('SaveMDStruct', res)
          if (res.success) {
            this.$message.success("创建成功")
          } else {
            this.$message.error("创建失败")
          }
          this.$emit("ok", { source: this.source })
          this.backToDefaultValue()
        })
      }
    },
    handleSecondStep () {
      return new Promise((resolve, reject) => {
        if (!this.source) {
          reject(new Error())
        }
        this.form.validateFields((errors, values) => {
          if (!errors) {
            this.mdl = values
            if (this.source === 'mingdao') {
              const { md_url: url, md_appKey: appKey, md_sign: sign } = values
              this.mdl._md = { url, appKey, sign }
              /*if (url === "" || appKey === "" || sign === "") {
                this.$message.warn("请正确填写 url, app key, sign")
                reject(new Error("url, appKey or sign is required"))
                return
              }*/
              getApp(this.mdl._md).then(res => {
                // console.log('second', res)
                if (res.success) {
                  this.md.worksheets = this.getCascadeData(res.data)
                  this.md.app = res.data
                }
              })
            }

            resolve()
          } else {
            this.form.setFields(errors)
            reject(new Error())
          }
        })
      })
    },
    getCascadeData (data) {
      const cascadeData = []
      data.sections.forEach((s, idx) => {
        const section = {
          value: idx,
          label: s.name,
          children: []
        }
        s.items.forEach(item => {
          section.children.push(
            {
              value: item.id,
              label: item.name
            }
          )
        })
        cascadeData.push(section)
      })
      return cascadeData
    },
    backToDefaultValue () {
      this.mdl = {}
      this.clearMdParams()
      this.current = 0
      this.source = ''
    }
  },
  created () {
    // 防止表单未注册
    fields.forEach(v => this.form.getFieldDecorator(v))

    // 获取options
    /*let param = { visualType: 'ThreeD' }
    getCascadeData(param).then(res => {
      if (res.code === 200) {
        this.options = res.data
      } else {
        this.$message.error(`获取分类失败`)
      }
    })*/

    // 当 model 发生改变时，为表单设置值
    this.$watch('model', () => {
      fields.forEach(v => this.form.getFieldDecorator(v))
      const data = pick(JSON.parse(JSON.stringify(this.model)), fields)
      if (Array.isArray(data.visualData) && data.visualData.length === 2) {
        data.visualData.unshift('ThreeD')
      }
      this.model && this.form.setFieldsValue(pick(this.model, fields))
    })
  }
}
</script>

<style lang="less" scoped>
  .steps-content {
    border-radius: 6px;
    min-height: 300px;
    //text-align: center;
  }

  .steps-action {
    margin-top: 24px;
    text-align: right;
  }
</style>
